{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e6553ccf",
   "metadata": {},
   "source": [
    "### Test for intersecting variants and genes "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca13817c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd \n",
    "import pysam \n",
    "from io import StringIO\n",
    "from pybedtools import BedTool\n",
    "from pathlib import Path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "843983fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "wkdir = \"/lustre/scratch126/humgen/projects/interval_rna/interval_rna_seq/thomasVDS/misexpression_v3\"\n",
    "wkdir_path = Path(wkdir)\n",
    "chrom = \"chr21\"\n",
    "vrnts_bed_path = wkdir_path.joinpath(\"4_vrnt_enrich/snp_indel_count_carriers/vrnts_bed/chr21_vrnts.bed\")\n",
    "genes_bed_path = wkdir_path.joinpath(\"4_vrnt_enrich/snp_indel_count_carriers/genes_bed/chr21_genes.bed\")\n",
    "window = 1000000\n",
    "root_dir_path = wkdir_path.joinpath(\"4_vrnt_enrich/snp_indel_count_carriers\")\n",
    "\n",
    "# constants \n",
    "window_intersect_cols={0:\"chrom_gene\", 1:\"start_gene\", 2:\"end_gene\", 3: \"gene_id\", \n",
    "                       4:\"score\", 5:\"strand\", 6:\"chrom_vrnt\", 7:\"start_vrnt\", 8:\"end_vrnt\", 9:\"vrnt_id\", 10:\"AF\"}\n",
    "\n",
    "# check root exists\n",
    "root_dir_path = Path(root_dir)\n",
    "root_dir_path.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "### Find variants intersecting gene windows \n",
    "intersect_bed_dir = root_dir_path.joinpath(\"intersect_beds\")\n",
    "Path(intersect_bed_dir).mkdir(parents=True, exist_ok=True)\n",
    "intersect_bed_path = intersect_bed_dir.joinpath(f\"{chrom}_gene_vrnts_intersect.tsv\")\n",
    "vrnts_bed = BedTool(vrnts_bed_path)\n",
    "gene_bed= BedTool(genes_bed_path)\n",
    "print(f\"Finding variant IDs in gene windows ...\")\n",
    "window_intersect_vrnts_str = StringIO(str(gene_bed.window(vrnts_bed, w=window)))\n",
    "window_intersect_vrnts_df = pd.read_csv(window_intersect_vrnts_str, sep=\"\\t\", header=None).rename(columns=window_intersect_cols)\n",
    "window_intersect_vrnts_df.to_csv(intersect_bed_path, sep=\"\\t\", index=False)\n",
    "print(f\"Completed.\")\n",
    "# genes with variants in windows \n",
    "intersect_genes_dir = root_dir_path.joinpath(\"intersect_genes\")\n",
    "Path(intersect_genes_dir).mkdir(parents=True, exist_ok=True)\n",
    "intersect_genes_path = intersect_genes_dir.joinpath(f\"{chrom}_gene_ids_intersect.txt\")\n",
    "intersect_gene_ids_list = window_intersect_vrnts_df.gene_id.unique()\n",
    "print(f\"{chrom} number of genes with variant in windows: {len(intersect_gene_ids_list)}\")\n",
    "# write gene list \n",
    "print(\"Writing genes to file ...\")\n",
    "with open(intersect_genes_path, 'w') as genes_out:\n",
    "    for gene_id in intersect_gene_ids_list: \n",
    "        genes_out.write(f\"{gene_id}\\n\")\n",
    "print(\"Completed.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
